package com.aijk.web.admin.controller.medical;

import com.aijk.commons.mijo.utils.PojoUtil;
import com.aijk.commons.utils.Collections3;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.ResidentTypeEnum;
import com.aijk.web.admin.utils.DateUtil;
import com.github.pagehelper.PageInfo;
import com.lifesea.familydoctor.api.FdStatisticBaseApi;
import com.lifesea.familydoctor.api.FdStatisticsApi;
import com.lifesea.familydoctor.model.FdStatisticBase;
import com.lifesea.familydoctor.model.ext.FdStatisticsGroup;
import com.lifesea.familydoctor.model.ext.FdStatisticsType;
import com.lifesea.familydoctor.model.qo.FdStatisticBaseQo;
import com.lifesea.familydoctor.model.qo.FdStatisticsGroupQo;
import com.lifesea.familydoctor.model.qo.FdStatisticsTypeQo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/statistics")
public class FdStatisticsController extends BaseController {

    @Autowired
    private FdStatisticsApi fdStatisticsApi;

    @Autowired
    private FdStatisticBaseApi fdStatisticBaseApi;

    /**
     * 统计接口
     */
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg downExcel(String regionId,String beginTime,String endTime,HttpServletRequest request){
        RetMsg regMsg = new RetMsg();
        FdStatisticsGroupQo qo = new FdStatisticsGroupQo();
        qo.setSignTab((byte) 2);
        if (regionId==null){
            regMsg.put("code", -1);
            regMsg.put("msg", "地区id为空");
            return regMsg;
        }else {
            qo.setRegionId(Integer.valueOf(regionId));
        }
        if (beginTime!=null){
            qo.setBeginTime(beginTime);
        }
        if (endTime!=null){
            qo.setEndTime(endTime);
        }

        //获取数据
        qo.setPageNo(1L);
        qo.setPageSize(20000L);

        //基数时间
        String baseTime ="";
        baseTime = DateUtil.dateFormate(new Date(), "yyyy-MM");
        List<String> baseTimeList = fdStatisticBaseApi.findTimes(null);
        if (Collections3.isNotEmpty(baseTimeList)) {
            baseTime = baseTimeList.get(0);
            if (beginTime!=null&&endTime!=null){
                DateFormat df = new SimpleDateFormat("yyyy-MM");
                try {
                    Date dt2 = df.parse(endTime);
                    for (String basetime:baseTimeList){
                        Date dt3 = df.parse(basetime);
                        if (dt2.getTime()>dt3.getTime()||dt2.getTime()==dt3.getTime()){
                            baseTime=basetime;
                            break;
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }




        PageInfo<FdStatisticsGroup> page = new PageInfo<>();
        if(qo.getRegionId() != null && qo.getRegionId() > 0){
            page = fdStatisticsApi.calculateStreetGroup(qo);
        }
        List<FdStatisticsGroup> groupList = page.getList();
        if(groupList.size() == 0){
            regMsg.put("code", -1);
            regMsg.put("msg", "查询为空");
            return regMsg;
        }
        List<HashMap> resultList = new ArrayList<>();

        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                if(StringUtils.isNotBlank(group.getStreetName()) && group.getStreetId() != null && group.getStreetId() > 0){
                    result.put("streetName", group.getStreetName());
                    typeQo.setStreetId(group.getStreetId());
                    typeQo.setTeamId(null);
                    typeQo.setReviewerUid(null);
                }
                if(StringUtils.isNotBlank(group.getTeamName()) && group.getTeamId() != null && group.getTeamId() > 0){
                    result.put("teamName", group.getTeamName());
                    typeQo.setTeamId(group.getTeamId());
                    typeQo.setStreetId(null);
                    typeQo.setReviewerUid(null);
                }
                if(StringUtils.isNotBlank(group.getServantName()) && group.getServantUid() != null && group.getServantUid() > 0){
                    result.put("memberName", group.getServantName());
                    typeQo.setReviewerUid(group.getServantUid());
                    typeQo.setStreetId(null);
                }
                /*if(group.getTeamNum() != null && group.getTeamNum() > 0)
                    result.put("teamNum", group.getTeamNum());*/
                //重点人群
                FdStatisticsType keyGroupType = fdStatisticsApi.calculateKeyGroup(typeQo);
                int keyGroup = 0;
                if(keyGroupType != null && keyGroupType.getNum() > 0){
                    keyGroup += keyGroupType.getNum();
                    result.put("keyGroup", keyGroupType.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                //各人群分类
                int noKeyGroup = 0;
                int keySignGroup = 0;
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());
                    if("10".equals(type.getType())){
                        noKeyGroup += type.getNum();
                    }
                    if(!"10".equals(type.getType())){
                        keySignGroup += type.getNum();
                    }
                }
                //辖区常住人口数
                result.put("signGroup",keyGroup + noKeyGroup);
                //辖区人群签约合计
                result.put("keySignGroup",keySignGroup);
                //查询基数
                if(group.getStreetId() != null && group.getStreetId() > 0){
                    getStatisticsBase(result, baseTime, noKeyGroup, keyGroup, group.getStreetId());
                }
                resultList.add(result);
            }
            regMsg.put("data",resultList);
            regMsg.put("code" , 0);
        } catch (Exception e) {
            e.printStackTrace();
            regMsg.put("code" , -1);
        }
        return regMsg;

    }

    /** 获取统计基数 **/
    private HashMap getStatisticsBase(HashMap result, String baseTime, int noKeyGroup, int keyGroup, int streetId){
        FdStatisticBaseQo baseQo = new FdStatisticBaseQo();
        if(StringUtils.isNotBlank(baseTime)){
            String[] timeArr = baseTime.split("-");
            baseQo.setYear(Integer.valueOf(timeArr[0]));
            baseQo.setMonth(Integer.valueOf(timeArr[1]));
        }
        baseQo.setRegionId(streetId);
        //重点人群基数
        int keyGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.keyGroup.getType());
        List<FdStatisticBase> keyBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(keyBaseList)) {
            keyGroupBase = keyBaseList.get(0).getValue();
        }
        //非重点人群基数
        int noKeyGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.noKeyGroup.getType());
        List<FdStatisticBase> noKeyBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(noKeyBaseList)) {
            noKeyGroupBase = noKeyBaseList.get(0).getValue();
        }
        //辖区常住人口基数
        result.put("rkBase",noKeyGroupBase + keyGroupBase);
        //孕产妇基数
        int pregnantGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.pregnantGroup.getType());
        List<FdStatisticBase> pregnantGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(noKeyBaseList)) {
            pregnantGroupBase = pregnantGroupBaseList.get(0).getValue();
        }
        result.put("pregnantGroupBase",pregnantGroupBase);
        //0-6岁儿童基数
        int childrenGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.childrenGroup.getType());
        List<FdStatisticBase> childrenGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(childrenGroupBaseList)) {
            childrenGroupBase = childrenGroupBaseList.get(0).getValue();
        }
        result.put("childrenGroupBase",childrenGroupBase);
        //65岁以上老年人基数
        int agedGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.agedGroup.getType());
        List<FdStatisticBase> agedGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(agedGroupBaseList)) {
            agedGroupBase = agedGroupBaseList.get(0).getValue();
        }
        result.put("agedGroupBase",agedGroupBase);
        //高血压人群基数
        int hypertensionGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.hypertensionGroup.getType());
        List<FdStatisticBase> hypertensionGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(hypertensionGroupBaseList)) {
            hypertensionGroupBase = hypertensionGroupBaseList.get(0).getValue();
        }
        result.put("hypertensionGroupBase",hypertensionGroupBase);
        //2型糖尿病患者基数
        int diabeticGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.diabeticGroup.getType());
        List<FdStatisticBase> diabeticGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(diabeticGroupBaseList)) {
            diabeticGroupBase = diabeticGroupBaseList.get(0).getValue();
        }
        result.put("diabeticGroupBase",diabeticGroupBase);
        //重性精神疾病患者基数
        int psychoticGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.psychoticGroup.getType());
        List<FdStatisticBase> psychoticGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(psychoticGroupBaseList)) {
            psychoticGroupBase = psychoticGroupBaseList.get(0).getValue();
        }
        result.put("psychoticGroupBase",psychoticGroupBase);
        //肺结核患者基数
        int tuberculosisGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.tuberculosisGroup.getType());
        List<FdStatisticBase> tuberculosisGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(tuberculosisGroupBaseList)) {
            tuberculosisGroupBase = tuberculosisGroupBaseList.get(0).getValue();
        }
        result.put("tuberculosisGroupBase",tuberculosisGroupBase);
        //残疾人基数
        int disabledGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.disabledGroup.getType());
        List<FdStatisticBase> disabledGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(disabledGroupBaseList)) {
            disabledGroupBase = disabledGroupBaseList.get(0).getValue();
        }
        result.put("disabledGroupBase",disabledGroupBase);
        //计生特殊家庭基数
        int familyPlanSpecialGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.familyPlanSpecialGroup.getType());
        List<FdStatisticBase> familyPlanSpecialGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(familyPlanSpecialGroupBaseList)) {
            familyPlanSpecialGroupBase = familyPlanSpecialGroupBaseList.get(0).getValue();
        }
        result.put("familyPlanSpecialGroupBase",familyPlanSpecialGroupBase);
        //农村建档立卡低收入人口基数
        int recordCardGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.recordCardGroup.getType());
        List<FdStatisticBase> recordCardGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(recordCardGroupBaseList)) {
            recordCardGroupBase = recordCardGroupBaseList.get(0).getValue();
        }
        result.put("recordCardGroupBase",recordCardGroupBase);
        //城镇低保人群基数
        int allowancesGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.allowancesGroup.getType());
        List<FdStatisticBase> allowancesGroupBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(allowancesGroupBaseList)) {
            allowancesGroupBase = allowancesGroupBaseList.get(0).getValue();
        }
        result.put("allowancesGroupBase",allowancesGroupBase);
        //合计基数
        result.put("groupBase",allowancesGroupBase+recordCardGroupBase+familyPlanSpecialGroupBase+disabledGroupBase+tuberculosisGroupBase+psychoticGroupBase+diabeticGroupBase+hypertensionGroupBase+agedGroupBase+childrenGroupBase+pregnantGroupBase);
        //签约率计算
        DecimalFormat df = new DecimalFormat("0.00");
        if(noKeyGroupBase > 0){
            result.put("noKeyGroupRate", df.format(((float)noKeyGroup/noKeyGroupBase)*100));
        }else{
            result.put("noKeyGroupRate", "0.00");
        }
        if(keyGroupBase > 0){
            result.put("keyGroupRate", df.format(((float)keyGroup/keyGroupBase)*100));
        }else{
            result.put("keyGroupRate", "0.00");
        }
        if((noKeyGroupBase+keyGroupBase) > 0){
            result.put("permanentGroupRate", df.format(((float)(noKeyGroup+keyGroup)/(noKeyGroupBase+keyGroupBase))*100));
        }else{
            result.put("permanentGroupRate", "0.00");
        }
        return result;
    }


}
